package com.hhq.usercenter.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hhq.common.util.HttpUtil;
import com.hhq.usercenter.config.WebProperties;
import com.hhq.usercenter.constants.LoginConstants;
import com.hhq.usercenter.domain.pojo.UserInfo;
import com.hhq.usercenter.domain.req.LoginReq;
import com.hhq.usercenter.mapper.UserMapper;
import com.hhq.usercenter.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/1/9 16:21
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private WebProperties webProperties;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public UserInfo login(LoginReq req) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        User user = (User) authenticate.getPrincipal();
        String token = IdUtil.fastSimpleUUID();
        UserInfo userInfo = new UserInfo(user.getUsername(), (Set<GrantedAuthority>) user.getAuthorities(), token);
        String tokenKey = webProperties.getSession().getPrefix() + StrUtil.C_COLON + token;
        userInfo.setToken(token);
        redisTemplate.opsForValue().set(tokenKey, userInfo, webProperties.getSession().getExpireTime(), TimeUnit.MINUTES);
        return userInfo;
    }

    @Override
    public void logout() {
        HttpServletRequest request = HttpUtil.request();
        String token = request.getHeader(LoginConstants.TOKEN);
        SecurityContextHolder.clearContext();
        redisTemplate.delete(webProperties.getSession().getPrefix() + StrUtil.C_COLON + token);
    }
}
